<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="$t('formgen.formQuestion.batchImport')"
    width="80%"
  >
    <div
      v-loading="loading"
      :element-loading-text="$t('common.processing')"
      class="batch-import-container"
    >
      <!-- 左侧题库树 -->
      <div class="left-panel">
        <div class="panel-title">{{ $t("formgen.formQuestion.bankList") }}</div>
        <el-tree
          ref="bankTreeRef"
          :data="formattedQuestionBankList"
          :default-expand-all="true"
          :props="treeProps"
          highlight-current
          node-key="id"
          @node-click="handleBankSelect"
        >
          <template #default="{ node, data }">
            <el-tooltip
              :content="node.label"
              :show-after="500"
              placement="top"
            >
              <span class="tree-node-label">
                <span class="label-text">{{ node.label }}</span>
                <span
                  v-if="data.questionCount !== undefined"
                  class="question-count"
                >
                  ({{ data.questionCount }})
                </span>
              </span>
            </el-tooltip>
          </template>
        </el-tree>
      </div>

      <!-- 右侧题目表格 -->
      <div class="right-panel">
        <div class="panel-header">
          <div class="panel-title">{{ $t("formgen.formQuestion.questionList") }}</div>
          <el-button
            :loading="loading"
            size="default"
            type="primary"
            @click="handleConfirm"
          >
            {{ $t("formgen.formQuestion.confirmImport") }}
          </el-button>
        </div>
        <el-table
          ref="tableRef"
          :data="questionList"
          height="500"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            :label="$t('formgen.formQuestion.questionTitle')"
            prop="label"
          />
          <el-table-column
            :label="$t('common.type')"
            prop="typeLabel"
          />
          <el-table-column
            :label="$t('common.createTime')"
            prop="createTime"
          />
        </el-table>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          :disabled="loading"
          @click="visible = false"
        >
          {{ $t("common.cancel") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { i18n } from "@/i18n";
import { getQuestionBankInfo, getQuestionBankItems } from "@/api/question/bank";
import { QuestionBankItem } from "@/api/question/bankItem";
import { ElMessage, ElMessageBox } from "element-plus";
import { formItemConvertData } from "@/views/formgen/utils/convert";
import { batchSaveProjectItem } from "@/views/formgen/api";
import { MessageUtil } from "@/utils/messageUtil";
import { formDesign } from "@/views/formgen/components/FormDesign/hooks/useFormDesign";

const visible = ref(false);
const formattedQuestionBankList = ref<any[]>([]);
const questionList = ref<QuestionBankItem[]>([]);
const selectedQuestions = ref<QuestionBankItem[]>([]);
const loading = ref(false);

const treeProps = {
  label: "name",
  children: "children"
};

const tableRef = ref();

// 显示对话框
const showDialog = () => {
  visible.value = true;
  loadQuestionBanks();
};

// 加载题库列表
const loadQuestionBanks = async () => {
  const res = await getQuestionBankInfo();
  // 格式化题库列表，添加分类节点
  formattedQuestionBankList.value = [
    {
      id: "personal",
      name: i18n.global.t("formgen.formQuestion.myQuestions"),
      children: res.data.personalQuestionBanks!.map(bank => ({
        ...bank,
        questionCount: bank.itemCount || 0
      }))
    },
    {
      id: "public",
      name: i18n.global.t("formgen.formQuestion.commonQuestions"),
      children: res.data.publicQuestionBanks!.map(bank => ({
        ...bank,
        questionCount: bank.itemCount || 0
      }))
    }
  ];
};

// 选择题库
const handleBankSelect = async (data: any) => {
  // 如果点击的是分类节点，不加载题目
  if (data.id === "personal" || data.id === "public") {
    questionList.value = [];
    return;
  }
  const res = await getQuestionBankItems(data.id);
  questionList.value = res.data;
};

// 表格选择变化
const handleSelectionChange = (selection: QuestionBankItem[]) => {
  selectedQuestions.value = selection;
};

const route = useRoute();

const { cloneComponent } = formDesign;

// 确认导入
const handleConfirm = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning(i18n.global.t("formgen.formQuestion.pleaseSelectQuestions"));
    return;
  }

  loading.value = true;
  try {
    const formKey = route.query.key as string;
    const fields = selectedQuestions.value.map((item, index) =>
      formItemConvertData(cloneComponent(item.scheme, false, index), formKey)
    );

    await batchSaveProjectItem({
      formKey: formKey,
      list: fields,
      operation: "add"
    });

    MessageUtil.success(i18n.global.t("common.saveSuccess"));
    // 清除表格选择
    tableRef.value?.clearSelection();

    // 添加确认提示
    ElMessageBox.confirm(i18n.global.t("formgen.formQuestion.importSuccessTip"), i18n.global.t("common.tip"), {
      confirmButtonText: i18n.global.t("formgen.formQuestion.refreshPage"),
      cancelButtonText: i18n.global.t("formgen.formQuestion.continueAdd"),
      type: "success"
    })
      .then(() => {
        // 用户点击"刷新页面"
        window.location.reload();
      })
      .catch(() => {
        // 用户点击"继续添加"
        showDialog(); // 重新打开对话框
      });
  } catch (error) {
    MessageUtil.error(i18n.global.t("common.saveFail"));
  } finally {
    loading.value = false;
  }
};

defineExpose({
  showDialog
});
</script>

<style lang="scss" scoped>
.batch-import-container {
  display: flex;
  gap: 20px;
  height: 600px;

  .left-panel,
  .right-panel {
    padding: 10px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
  }

  .left-panel {
    width: 258px;
    overflow: auto;
  }

  .right-panel {
    flex: 1;
    overflow: auto;
  }

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .panel-title {
    font-size: 16px;
    font-weight: bold;
  }

  .question-count {
    color: var(--el-text-color-secondary);
    font-size: 13px;
    margin-left: 4px;
  }
}

.tree-node-label {
  display: flex;
  align-items: center;
  width: 100%;

  .label-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 150px; // 可以根据实际需要调整
  }

  .question-count {
    color: var(--el-text-color-secondary);
    font-size: 13px;
    margin-left: 4px;
    flex-shrink: 0;
  }
}
</style>
